package cn.ultrarisk.scadmin.manager.web.controller.solr;

import cn.ultrarisk.mybatis.extension.domain.Page;
import cn.ultrarisk.mybatis.extension.query.Query;
import cn.ultrarisk.scadmin.manager.biz.monitor.dao.SolrNodeMonitorDAO;
import cn.ultrarisk.scadmin.manager.biz.monitor.entity.SolrNodeMonitor;
import cn.ultrarisk.scadmin.manager.biz.solr.dao.SolrNodeDAO;
import cn.ultrarisk.scadmin.manager.biz.solr.entity.SolrNode;
import cn.ultrarisk.scadmin.manager.biz.solr.service.SolrNodeService;
import cn.ultrarisk.scadmin.manager.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * NodeController
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/4/17
 * @since V1.0
 */
@Controller
@RequestMapping(value = "/solr/node")
public class NodeController extends BaseController {

    @Autowired
    private SolrNodeDAO solrNodeDAO;
    @Autowired
    private SolrNodeService solrNodeService;
    @Autowired
    private SolrNodeMonitorDAO solrNodeMonitorDAO;

    @ResponseBody
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResponseEntity<Map<String, Object>> list(String host, Boolean available, String solrVersion, int pageNo, int pageSize) {
        Map<String, Object> map = new HashMap<String, Object>();
        Page<SolrNode> paged = solrNodeDAO.findPage(host, available, solrVersion, pageNo, pageSize);
        map.put("paged", paged);

        List<Integer> nodeIds = new ArrayList<Integer>();
        for (SolrNode node : paged.getList()) {
            nodeIds.add(node.getId());
        }
        if (nodeIds.size() > 0) {
            Map<Integer, SolrNodeMonitor> monitorMap = solrNodeMonitorDAO.getNewest(nodeIds);
            map.put("monitorMap", monitorMap);
        }
        map.put("hosts", solrNodeDAO.findColumn(new Query(), SolrNode.HOST, true, true));
        map.put("solrVersions", solrNodeDAO.findColumn(new Query(), SolrNode.SOLR_SPEC_VERSION, true, true));
        return getOkResponseEntity(map);
    }

    @ResponseBody
    @RequestMapping(value = "/all", method = RequestMethod.GET)
    public ResponseEntity<List<SolrNode>> findAll() {
        List<SolrNode> nodes = solrNodeDAO.findAvailable(null);
        return getOkResponseEntity(nodes);
    }

    @ResponseBody
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<String> delete(@PathVariable("id") Integer id) {
        solrNodeService.delete(id);
        return getOkResponseEntity();
    }
}
